package com.example.sharedelementdemo

import android.app.SharedElementCallback
import android.os.Bundle
import android.util.Log
import android.view.MotionEvent
import android.view.View
import android.view.WindowManager
import android.widget.ImageView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.dragclosehelper.library.DragCloseHelper
import com.dragclosehelper.library.DragCloseHelper.DragCloseListener


class MainActivity2 : AppCompatActivity(), MyAdapter2.CoilCallBack {
    private lateinit var viewPager2: ViewPager2
    private lateinit var adapter: MyAdapter2
    private var selectPosition = 0
    private val mipmaps = ArrayList<LocalBean>()
    private lateinit var layoutManager: LinearLayoutManager

    var dragCloseHelper: DragCloseHelper? = null
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
//        val lp=window.attributes
//        lp.alpha=0.5f

//        window.attributes=lp

//隐藏状态栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
//透明导航栏
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        setContentView(R.layout.activity_main2)
        viewPager2 = findViewById(R.id.vp)

        selectPosition = intent.extras!!["position"] as Int
//        initDrawHelp()
        postponeEnterTransition() //延缓执行 然后在fragment里面的控件加载完成后start

        initRv()

        setEnterSharedElementCallback(object : SharedElementCallback() {
            override fun onMapSharedElements(
                names: MutableList<String>?,
                sharedElements: MutableMap<String, View>?
            ) {
                super.onMapSharedElements(names, sharedElements)
                Log.d("ActivityOptionsCompat", "EnterSharedElementCallback222")
                val itemView: View? = layoutManager.findViewByPosition(selectPosition)
                val imageView = itemView?.findViewById<ImageView>(R.id.item_image)
                names?.clear()
                sharedElements!!.clear()
                imageView?.let {
                    sharedElements[mipmaps[selectPosition].tag] = imageView
                }
            }
        })

    }

    private fun initDrawHelp() {
        dragCloseHelper = DragCloseHelper(this)
        dragCloseHelper?.setShareElementMode(true);
        dragCloseHelper?.setDragCloseListener(object : DragCloseListener {
            override fun intercept(): Boolean {
                //默认false 不拦截。比如图片在放大状态，是不需要执行拖拽动画的等等。
                return false
            }

            override fun dragStart() {
                //拖拽开始。可以在此额外处理一些逻辑
//                layoutManager.findViewByPosition(selectPosition)?.findViewById<ImageView>(R.id.item_image)?.setAlpha(1f)
            }

            override fun dragging(percent: Float) {
                //拖拽中。percent当前的进度，取值0-1，可以在此额外处理一些逻辑
            }

            override fun dragCancel() {
                //拖拽取消，会自动复原。可以在此额外处理一些逻辑
            }

            override fun dragClose(isShareElementMode: Boolean) {
                //拖拽关闭，如果是共享元素的页面，需要执行activity的onBackPressed方法，注意如果使用finish方法，则返回的时候没有共享元素的返回动画
                if (isShareElementMode) {
                    onBackPressed()
                }
            }
        })

        dragCloseHelper?.setDragCloseViews(
            viewPager2,
            layoutManager.findViewByPosition(selectPosition)?.findViewById(R.id.item_image)
        );

        dragCloseHelper?.setClickListener { view, isLongClick ->
            //isLongClick 是否为长按事件。建议长按使用库中此方法，单击不建议使用（建议直接写在宿主代码中）。
        }
    }

    private fun initRv() {
        adapter = MyAdapter2(this)
        mipmaps.add(LocalBean(R.mipmap.wangze1, "0"))
        mipmaps.add(LocalBean(R.mipmap.other1, "1"))
        mipmaps.add(LocalBean(R.mipmap.other2, "2"))
        mipmaps.add(LocalBean(R.mipmap.wangze2, "3"))
        mipmaps.add(LocalBean(R.mipmap.other3, "4"))
        mipmaps.add(LocalBean(R.mipmap.other4, "5"))
        mipmaps.add(LocalBean(R.mipmap.other5, "6"))
        mipmaps.add(LocalBean(R.mipmap.wangze3, "7"))
        mipmaps.add(LocalBean(R.mipmap.wangze4, "8"))
        mipmaps.add(LocalBean(R.mipmap.wangze5, "9"))
        mipmaps.add(LocalBean(R.mipmap.wangze6, "10"))
        mipmaps.add(LocalBean(R.mipmap.wangze7, "11"))
        mipmaps.add(LocalBean(R.mipmap.wangze8, "12"))
        mipmaps.add(LocalBean(R.mipmap.wangze9, "13"))
        mipmaps.add(LocalBean(R.mipmap.wangze10, "14"))
        viewPager2.adapter = adapter

        adapter.submitList(mipmaps)
        viewPager2.setCurrentItem(selectPosition, false)

        viewPager2.apply {
            val recyclerView = getChildAt(0) as RecyclerView
            layoutManager = recyclerView.layoutManager as LinearLayoutManager
        }


        viewPager2.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) {
                super.onPageScrolled(position, positionOffset, positionOffsetPixels)

            }

            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                selectPosition = position
                MainActivity.exitLiveData.postValue(position.toString())

                dragCloseHelper?.setDragCloseViews(
                    viewPager2,
                    layoutManager.findViewByPosition(selectPosition)?.findViewById(R.id.item_image)
                );
            }

            override fun onPageScrollStateChanged(state: Int) {
                super.onPageScrollStateChanged(state)

            }
        })

    }

    override fun dispatchTouchEvent(event: MotionEvent?): Boolean {
        if (dragCloseHelper == null) {
            initDrawHelp()
        }
        return if (dragCloseHelper?.handleEvent(event) == true) {
            true
        } else {
            super.dispatchTouchEvent(event)
        }
    }

    override fun loadSuccess() {
        startPostponedEnterTransition()
    }

}